//Tan Kok Hui
import java.io.*;
import java.util.Vector;

public class FileIO {
	private File textFile;
	private String textFileName;

	public FileIO(String fileName) {
		assert(fileName != null);
		
		textFile = new File(fileName);
		textFileName = fileName;
	}

	public boolean fileExists() {
		return textFile.exists();
	}

	public Vector<Task> readFromFile() {
		Vector<Task> tasksInFile = new Vector<Task>();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(textFile));
		} catch (FileNotFoundException e) {
			System.out.println(e);
		}
		String s = "";

		try {
			while ((s = reader.readLine()) != null) {
				String[] line = s.split(",");
				tasksInFile.add(new Task(line[0], line[1], line[2], line[3]));
			}
		} catch (IOException e) {
			System.out.println(e);
		}

		return tasksInFile;
	}

	public void writeToFile(Vector<Task> tasks) {
		assert(tasks != null);
		if (!fileExists())
			textFile = new File(textFileName);
		
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(textFile));

			for (int i = 0; i < tasks.size(); i++) {
				writer.write(tasks.get(i).getDescription() + ","
						+ tasks.get(i).getDate() + "," + tasks.get(i).getTime()
						+ "," + tasks.get(i).getID());
				writer.newLine();
			}

			writer.close();

			return;
		}
		catch (IOException e) {
			System.out.println(e);
		}
	}
}
